package com.pengheng.example1;

import org.bouncycastle.asn1.*;

import java.io.IOException;

public class Person implements ASN1Encodable {
    private DERUTF8String name;
    private ASN1Integer age;
    private DERUTF8String address;

    public Person(DERUTF8String name, ASN1Integer age) {
        this.name = name;
        this.age = age;
    }

    public Person(DERUTF8String name, ASN1Integer age, DERUTF8String address) {
        this(name, age);
        this.address = address;
    }

    public static Person getInstance(Object obj) throws IOException {
        if (obj instanceof Person) {
            return (Person) obj;
        } else if (obj != null) {
            ASN1Sequence seq = ASN1Sequence.getInstance(obj);
            DERUTF8String name = DERUTF8String.getInstance(seq.getObjectAt(0));
            ASN1Integer age = ASN1Integer.getInstance(seq.getObjectAt(1));
            DERUTF8String address = null;
            if (seq.size() > 2) {
                DERTaggedObject taggedObject = (DERTaggedObject) seq.getObjectAt(2);
                address = DERUTF8String.getInstance(taggedObject.getObject());
            }
            return new Person(name, age, address);
        } else {
            return null;
        }
    }

    public DERUTF8String getName() {
        return name;
    }

    public ASN1Integer getAge() {
        return age;
    }

    public DERUTF8String getAddress() {
        return address;
    }

    @Override
    public ASN1Sequence toASN1Primitive() {
        if (address == null) {
            return new DERSequence(new ASN1Encodable[]{name, age});
        } else {
            DERTaggedObject taggedObject = new DERTaggedObject(0, address);
            return new DERSequence(new ASN1Encodable[]{name, age, taggedObject});
        }
    }
}